﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Globalization;
using System.Collections;

namespace monitor_client
{
    public delegate IPAddress monitor4to2(IPAddress ip);
    public delegate void fclose(bool b);
    public delegate void form_delegate(Form f);
    public delegate void Icon_invoke(PictureBox a, int b);
    public delegate void NewIpFor4FormDelegate(IPAddress ip);
    public delegate void f4ChangeEventDelegate(NewIpFor4FormDelegate a, bool b);

    public partial class MainForm : Form
    {
        class ListViewItemComparer : IComparer
        {
            private int col;
            public ListViewItemComparer(int column)
            {
                if (column == 0)
                    col = 1;
                else
                    col = column;

            }
            public int Compare(object x, object y)
            {
                int ret = 0;
                DateTime dt1, dt2;
                string dtx = ((ListViewItem)x).SubItems[col].Text;
                string dty = ((ListViewItem)y).SubItems[col].Text;
                //--------------------------Сортировка по столбцам, содержащим дату
                if (DateTime.TryParseExact(dtx, "dd.MM/HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt1))
                {
                    if (dty == "Нет данных")
                    {
                        if (!comp)
                            dt2 = DateTime.ParseExact("01.01/00:00", "dd.MM/HH:mm", CultureInfo.InvariantCulture);
                        else
                            dt2 = DateTime.ParseExact("31.12/00:00", "dd.MM/HH:mm", CultureInfo.InvariantCulture);
                    }
                    /*else
                        dt2 = DateTime.ParseExact(((ListViewItem)y).SubItems[col].Text, "dd.MM/HH:mm", CultureInfo.InvariantCulture);
                    ret = DateTime.Compare(dt1, dt2);*/
                    else
                    {
                        if (DateTime.TryParseExact(dty, "dd.MM/HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt2))
                            ret = DateTime.Compare(dt1, dt2);
                        else
                            ret = -1;
                    }
                }
                else if (dtx == "Нет данных")
                {
                    if (!comp)
                        dt1 = DateTime.ParseExact("01.01/00:00", "dd.MM/HH:mm", CultureInfo.InvariantCulture);
                    else
                        dt1 = DateTime.ParseExact("31.12/00:00", "dd.MM/HH:mm", CultureInfo.InvariantCulture);
                    if (dty == "Нет данных")
                        dt2 = DateTime.ParseExact("01.01/00:00", "dd.MM/HH:mm", CultureInfo.InvariantCulture);
                    /*else
                        dt2 = DateTime.ParseExact(((ListViewItem)y).SubItems[col].Text, "dd.MM/HH:mm", CultureInfo.InvariantCulture);
                    ret = DateTime.Compare(dt1, dt2);*/
                    else
                    {
                        if (DateTime.TryParseExact(dty, "dd.MM/HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt2))
                            ret = DateTime.Compare(dt1, dt2);
                        else
                            ret = -1;
                    }
                }
                //--------------------------
                else
                    ret = String.Compare(dtx, dty);
                if (!comp)
                    ret *= -1;
                return ret;
            }
        }

        

        public bool check_state(byte[] lstate, byte[] errors)
        {
            for(int i = 0; i < lstate.Length; i++)
            {
                if(lstate[i] != errors[i])
                    return false;
            }
            return true;
        }

        JournalForm form6;
        IzmersMonitoringForm form4;
        Icons[] icon;
        int count_con = 2;                              //количество попыток соединения с измерителями
        int dev_types = 2;                              //номенклатура устройств в сети
        static bool comp = false;
        string ipstr = "";
        f2close Initiate_CLOSING;
        rec_options options = new rec_options();
        string[] read_tree;
        TreeNode[] nodes = new TreeNode[2];
        int izmers_count = 0;
        int analiz_count = 0;
        int icon_count = 0;
        Icons_p icon_p = new Icons_p();
        System.Windows.Forms.Timer izmers_req;
        System.Windows.Forms.Timer analiz_req;
        Thread Timer_I;
        Thread Timer_A;
        bool wait_i_trig = false;
        bool wait_a_trig = false;
        izmer[] izmers = new izmer[100];
        analiz[] analiz = new analiz[100];
        Socket izm_soc;
        delegate void izm_lrem(ListViewItem a);
        delegate void izm_ldel(ListViewItem a);
        //delegate void izm_lerr(izmer a, string err);
        delegate void izm_cerr(ListViewItem a, string err, string terr);
        byte b1 = (byte)1;
        byte b0 = (byte)0;
        private event NewIpFor4FormDelegate AddIzmer;
        fclose FClose;
        int izm_lport = 25001;
        int list_c = 0;
        string curListViewItemIP = "";
        string curListViewItemName = "";


        public MainForm(f2close CLOSING_SENDER, rec_options sender_options)
        {
            
            Initiate_CLOSING = CLOSING_SENDER;
            InitializeComponent();
            this.ResizeRedraw = true;
            options = sender_options;
            izm_soc = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            izm_soc.ReceiveTimeout = 1200;            
            listView1.View = View.Details;
            listView1.ShowItemToolTips = true;
            listView1.FullRowSelect = true;
            listView1.Columns.Add("N");
            listView1.Columns[listView1.Columns.Count - 1].Width = 30;
            listView1.Columns.Add("Дата/Время");
            listView1.Columns[listView1.Columns.Count - 1].Width = 80;
            listView1.Columns.Add("Область");
            listView1.Columns[listView1.Columns.Count - 1].Width = 90;
            listView1.Columns.Add("Зона выделения");
            listView1.Columns[listView1.Columns.Count - 1].Width = 100;
            listView1.Columns.Add("Название");
            listView1.Columns[listView1.Columns.Count - 1].Width = 130;
            listView1.Columns.Add("Группа");
            listView1.Columns[listView1.Columns.Count - 1].Width = 90;
            listView1.Columns.Add("Событие");
            listView1.Columns[listView1.Columns.Count - 1].Width = 110;
        }

        bool f4 = false;
        bool f6 = false;

        void f4close(bool param)
        {
            f4 = param;
            //form4.Close();
        }

        void f4ChangeEvent(NewIpFor4FormDelegate func, bool add)
        {
            if (add)
                AddIzmer += func;
            else
                AddIzmer -= func;
        }

        void f6close(bool param)
        {
            f6 = param;
        }

        void form_send(Form param)
        {
            param = this;
        }

        private void icon_set(PictureBox icon, int type)
        {
            switch (type)
            {
                case 1:
                    icon.Image = Image.FromFile(icon_p.p_green);                    
                    break;
                case 2:
                    icon.Image = Image.FromFile(icon_p.p_yellow);
                    break;
                case 3:
                    icon.Image = Image.FromFile(icon_p.p_red);
                    break;
                case 4:
                    icon.Image = Image.FromFile(icon_p.p_cross);
                    break;
                case 5:
                    icon.Image = Image.FromFile(icon_p.p_lost);
                    break;
            }
            icon.Update();
        }

        private int get_icon_num(Icons[] icon, string name)
        {
            for (int i = 0; i < icon.Length; i++)
            {
                if (icon[i].name.Text == name)
                    return i;
            }
            return -1;
        }

        private void выходToolStripMenuItem_Click(object sender, EventArgs e)           //Выход из программы
        {
            DialogResult res = MessageBox.Show("Вы уверены, что хотите выйти?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (res == DialogResult.No)
                return;
            try
            {
                analiz_req.Stop();
                Timer_A.Abort();
                Timer_A.Join();
                izmers_req.Stop();
                Timer_I.Abort();
                Timer_I.Join();
            }
            catch (NullReferenceException)
            { }
            if (f6)
            {
                form6.Close();
            }
            Initiate_CLOSING();
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            //---------------------------Легенда----------------------------
            //Зеленый
            pictureBox4.Image = Image.FromFile(icon_p.p_green);
            label1.Text = "- Нет ошибок и предупреждений.";
            //Желтый
            pictureBox5.Image = Image.FromFile(icon_p.p_yellow);
            label2.Text = "- Есть предупреждения.";
            this.Enabled = false;
            //Красный
            pictureBox6.Image = Image.FromFile(icon_p.p_red);
            label3.Text = "- Есть ошибки.";
            //Крест
            pictureBox7.Image = Image.FromFile(icon_p.p_cross);
            label4.Text = "- Есть критические ошибки.";
            //Вопрос
            pictureBox8.Image = Image.FromFile(icon_p.p_lost);
            label5.Text = "- Нет связи с устройством.";
            //Серый
            pictureBox9.Image = Image.FromFile(icon_p.p_grey);
            label6.Text = "- Устройство не активно.";
            //----------Иконки на карте-------------------------------------
            string oblast;
            string[] icon_pos = new string[1];
            bool showText;
            int adder = 0;
            //Доделать!!!
            if (options.oblast.Length == 1 && options.access != 1)
            {
                oblast = options.oblast[0];
                pictureBox1.Image = Image.FromFile(@"resources\mapsPic\" + oblast + ".jpg");
                icon_pos = File.ReadAllLines(@"resources\positions_" + oblast, Encoding.GetEncoding("Windows-1251"));
                showText = true;
            }
            else
            {
                showText = false;
                pictureBox1.Image = Image.FromFile(@"resources\mapsPic\belarus.jpg");
                icon_pos = File.ReadAllLines(@"resources\positions_belarus", Encoding.GetEncoding("Windows-1251"));
                adder = 15;
            }
            icon = new Icons[icon_pos.Length - 1];
            int m, n, posx, posy, sizehalf;
            string text;
            icon_count = -1;
            for (int h = 1; h < icon_pos.Length; h++)
            {
                if (icon_pos[h].Substring(0, 5) == "РТПС ")
                {
                    icon_count++;
                    m = 0;
                    while (icon_pos[h].Substring(m, 1) != "=")
                        m++;
                    text = icon_pos[h].Substring(0, m);
                    m++;
                    n = m;
                    while (icon_pos[h].Substring(n, 1) != ",")
                        n++;
                    posx = Int32.Parse(icon_pos[h].Substring(m, n - m));
                    posy = Int32.Parse(icon_pos[h].Substring(n + 1));
                    icon[icon_count] = new Icons();
                    //------иконка------
                    icon[icon_count].icon = new PictureBox();
                    icon[icon_count].icon.Location = new Point(posx - pictureBox1.Location.X, posy - pictureBox1.Location.Y + adder);
                    icon[icon_count].icon.Image = Image.FromFile(icon_p.p_grey);
                    icon[icon_count].icon.SizeMode = PictureBoxSizeMode.AutoSize;
                    icon[icon_count].icon.Name = Convert.ToString(icon_count);
                    icon[icon_count].icon.MouseClick += new MouseEventHandler(icon_MouseClick);
                    if (!showText)
                    {
                        icon[icon_count].icon.MouseEnter += new EventHandler(icon_MouseEnter);
                        icon[icon_count].icon.MouseLeave += new EventHandler(icon_MouseLeave);
                    }
                    icon[icon_count].icon.Tag = showText;
                    icon[icon_count].icon.Enabled = true;
                    icon[icon_count].icon.Visible = true;
                    this.Controls.Add(icon[icon_count].icon);
                    icon[icon_count].icon.Parent = pictureBox1;
                    icon[icon_count].icon.BackColor = Color.Transparent;
                    icon[icon_count].icon.BringToFront();
                    //------подпись-----
                    icon[icon_count].name = new Label();
                    icon[icon_count].name.Tag = showText;
                    icon[icon_count].name.Text = text;
                    icon[icon_count].name.BorderStyle = BorderStyle.FixedSingle;
                    icon[icon_count].name.Size = new Size(icon[icon_count].name.PreferredWidth, icon[icon_count].name.PreferredHeight);
                    sizehalf = icon[icon_count].name.Size.Width / 2 - 8;
                    icon[icon_count].name.Location = new Point(posx - sizehalf, posy + 19 + adder);
                    this.Controls.Add(icon[icon_count].name);
                    icon[icon_count].name.Visible = showText;
                    icon[icon_count].name.BringToFront();
                }
            }
            /*
            icon[icon_count] = new Icons();
            icon[icon_count].icon = new PictureBox();
            icon[icon_count].icon.Visible = false;
            icon[icon_count].name = new Label();
            icon[icon_count].name.Visible = false;
             */

            //----------Создание файлов и построение дерева-----------------
            
            string ipstr = "", blr = "", dev = "", node_text = "", obl = "";
            string[] blr_write = new string[1], blr_read; 
            int i = 0, count, blr_count = 0, t = 0, blr_num = 0;
            int u = 0, u1;

            TreeNode[] treeNodes = new TreeNode[options.oblast.Length];
            if (File.Exists(@"resources\adresses_temp.ini"))
                File.Delete(@"resources\adresses_temp.ini");

            for (int gh = 0; gh < options.oblast.Length; gh++)
            {
                count = -1;
                options.devices = new TreeNode[dev_types];
                read_tree = File.ReadAllLines(@"resources\" + options.oblast[gh].Substring(0) + ".ini", Encoding.GetEncoding("Windows-1251"));
                File.Delete(@"resources\" + options.oblast[gh].Substring(0) + ".ini");
                StreamWriter ws = new StreamWriter(@"resources\adresses_temp.ini", true);
                t = 0;
                FileStream fs = new FileStream(@"resources\blr_tmp", FileMode.Create, FileAccess.ReadWrite);
                blr_count = 0;
                i = 0;
                int tmp_analiz_count = 0;
                int tmp_izmers_count = 0;
                while (i < read_tree.Length)
                {
                    switch (read_tree[i])
                    {
                        case "[Измерители]":
                            File.WriteAllText(@"resources\selzone.ini", "[Select zones]\r\n");
                            count++;
                            dev = "izm";
                            options.devices[count] = new TreeNode();
                            options.devices[count].Text = "Измерители";
                            i++;
                            break;
                        case "[Анализаторы]":
                            count++;
                            dev = "anal";
                            options.devices[count] = new TreeNode();
                            options.devices[count].Text = "Анализаторы";
                            i++;
                            break;
                        case "":
                            i++;
                            break;
                        default:
                            u = 0; u1 = 0;
                            while (read_tree[i][u] != '=')
                                u++;
                            node_text = read_tree[i].Substring(0, u);
                            u++;
                            ipstr = read_tree[i].Substring(u, read_tree[i].Length - u);
                            if (dev == "izm")
                            {
                                u1 = u;
                                while (read_tree[i][u1] != ',')
                                    u1++;
                                ipstr = read_tree[i].Substring(u, u1 - u);

                                u1++;
                                while (read_tree[i].Substring(u, 3) != "BLR")
                                    u++;
                                try
                                {
                                    blr = read_tree[i].Substring(u, 5);
                                }
                                catch (ArgumentOutOfRangeException)
                                {
                                    blr = read_tree[i].Substring(u, 4);
                                }
                                if (blr_count == 0)
                                {
                                    byte[] bt = new byte[7];
                                    bt[0] = (byte)blr[0];
                                    bt[1] = (byte)blr[1];
                                    bt[2] = (byte)blr[2];
                                    bt[3] = (byte)blr[3];
                                    bt[4] = (byte)blr[4];
                                    bt[5] = (byte)blr_count;
                                    bt[6] = (byte)'\n';
                                    fs.Write(bt, 0, 7);
                                    options.devices[count].Nodes.Add(blr);
                                    blr_num = t;
                                    blr_count++;
                                    //devices[count, obn].Nodes.Add(blr);
                                }
                                else
                                {

                                    string[] str = new string[blr_count];
                                    fs.Close();
                                    str = File.ReadAllLines(@"resources\blr_tmp");
                                    //fs = new FileStream(@"resources\blr_tmp", FileMode.Open, FileAccess.ReadWrite);
                                    fs = new FileStream(@"resources\blr_tmp", FileMode.Append, FileAccess.Write);
                                    for (t = 0; t < blr_count; t++)
                                    {
                                        if (str[t].Substring(0, 5).Equals(blr))
                                            break;
                                    }
                                    if (t == blr_count)
                                    {
                                        byte[] bt = new byte[7];
                                        bt[0] = (byte)blr[0];
                                        bt[1] = (byte)blr[1];
                                        bt[2] = (byte)blr[2];
                                        bt[3] = (byte)blr[3];
                                        bt[4] = (byte)blr[4];
                                        bt[5] = (byte)blr_count;
                                        bt[6] = (byte)'\n';
                                        fs.Write(bt, 0, 7);
                                        blr_num = t;
                                        blr_count++;
                                        options.devices[count].Nodes.Add(blr);
                                    }
                                    else
                                    {
                                        blr_num = t;
                                    }
                                }
                                fs.Close();

                                izmers[izmers_count] = new izmer();
                                izmers[izmers_count].ipe = new IPEndPoint(IPAddress.Parse(ipstr), izmers[izmers_count].port);
                                izmers[izmers_count].name = node_text;
                                izmers[izmers_count].ico = get_icon_num(icon, izmers[izmers_count].name);
                                if (izmers[izmers_count].ico == -1)
                                {
                                    MessageBox.Show("На карте нет измерителя с названием " + izmers[izmers_count].name);
                                    izmers[izmers_count].ico = icon_count;
                                    icon[icon_count].exist = false;
                                }
                                izmers[izmers_count].blr = blr;
                                izmers[izmers_count].show = false;
                                izmers[izmers_count].lstate[0] = b0;
                                izmers[izmers_count].lstate[1] = b0;
                                izmers[izmers_count].lstate[2] = b0;
                                izmers[izmers_count].lstate[3] = b0;
                                tmp_izmers_count++;
                                izmers_count++;
                                ws.WriteLine(ipstr + "=" + node_text + "," + blr);                              //Запись адресов
                                //-------------------------------
                                u = 1;
                                blr_read = File.ReadAllLines(@"resources\selzone.ini");
                                while (u <= blr_read.Length)
                                {
                                    if (u == blr_read.Length)
                                    {
                                        blr_write = new string[blr_read.Length + 1];
                                        for (int j = 0; j < blr_read.Length; j++)
                                            blr_write[j] = blr_read[j];
                                        blr_write[u] += blr + "=" + ipstr;
                                    }
                                    else
                                    {
                                        if (blr_read[u].Substring(0, 5) == blr)
                                        {
                                            blr_read[u] += "," + ipstr;
                                            for (int j = 0; j < blr_read.Length; j++)
                                                blr_write[j] = blr_read[j];
                                        }
                                    }
                                    u++;
                                }
                                File.WriteAllLines(@"resources\selzone.ini", blr_write);
                                //-------------------------------
                                options.devices[count].Nodes[blr_num].Nodes.Add(node_text).Tag = ipstr;
                            }
                            else
                                if (dev == "anal")
                                {
                                    analiz[analiz_count] = new analiz();
                                    analiz[analiz_count].ipe = IPAddress.Parse(ipstr);
                                    analiz[analiz_count].name = node_text;
                                    analiz[analiz_count].ico = get_icon_num(icon, analiz[analiz_count].name);
                                    if (analiz[analiz_count].ico == -1)
                                    {
                                        MessageBox.Show("На карте нет анализатора с названием " + analiz[analiz_count].name);
                                        analiz[analiz_count].ico = icon_count;
                                        icon[icon_count].exist = false;
                                    }
                                    analiz[analiz_count].show = false;
                                    analiz[analiz_count].lstate[0] = 1;
                                    analiz[analiz_count].lstate[1] = 1;
                                    tmp_analiz_count++;
                                    analiz_count++;
                                    //StreamWriter analiz_sw = new StreamWriter(@"resources\adresses_an_temp.ini");
                                    ws.WriteLine(ipstr + "=" + node_text);
                                    //analiz_sw.Close();
                                    options.devices[count].Nodes.Add(node_text).Tag = ipstr;
                                }

                            i++;
                            break;
                    }
                }
                fs.Close();
                File.Delete(@"resources\blr_tmp");
                ws.Close();
                switch (options.oblast[gh])
                {
                    case "brest":
                        obl = "Брестская";
                        break;
                    case "viteb":
                        obl = "Витебская";
                        break;
                    case "gomel":
                        obl = "Гомельская";
                        break;
                    case "grodn":
                        obl = "Гродненская";
                        break;
                    case "minsk":
                        obl = "Минская";
                        break;
                    case "mogil":
                        obl = "Могилевская";
                        break;
                }
                for (i = izmers_count - tmp_izmers_count; i < izmers_count; i++)
                {
                    izmers[i].obl = obl;
                }
                for (i = analiz_count - tmp_analiz_count; i < analiz_count; i++)
                {
                    analiz[i].obl = obl;
                }
                treeNodes[gh] = new TreeNode(obl);
                treeNodes[gh].Nodes.AddRange(options.devices);
            }
            
            treeView1.BeginUpdate();
            for (int j = 0; j < options.oblast.Length; j++)
            {
                treeView1.Nodes.Add(treeNodes[j]);
            }

            treeView1.ExpandAll();
            treeView1.EndUpdate();
            //------------------------запуск мониторинга-------
            listView1.View = View.Details;
            IPAddress ip = IPAddress.Any;
            IPEndPoint lpe;
            while (true)
            {
                try
                {
                    lpe = new IPEndPoint(ip, izm_lport);
                    izm_soc.Bind(lpe);
                    break;
                }
                catch (SocketException)
                {
                    izm_lport--;
                }
            }
            izmers_req = new System.Windows.Forms.Timer();
            izmers_req.Interval = 2000;
            izmers_req.Enabled = true;
            izmers_req.Tick += new EventHandler(tim_I_tick);
            izmers_req.Start();

            analiz_req = new System.Windows.Forms.Timer();
            analiz_req.Interval = 2000;
            analiz_req.Enabled = true;
            analiz_req.Tick += new EventHandler(tim_A_tick);
            analiz_req.Start();
            //-------------------------------------------------
            this.Enabled = true;            
        }

        void AddMouseEvents(PictureBox pic)
        {
            pic.MouseEnter += new EventHandler(icon_MouseEnter);
            pic.MouseLeave += new EventHandler(icon_MouseLeave);
        }

        void RemoveMouseEvents(PictureBox pic)
        {
            pic.MouseEnter -= icon_MouseEnter;
            pic.MouseLeave -= icon_MouseLeave;
        }

        void icon_MouseClick(object sender, MouseEventArgs e)
        {
            int i = Int32.Parse(((PictureBox)sender).Name);
            PictureBox pic = ((PictureBox)sender);
            if (!(bool)pic.Tag)
            {
                pic.Tag = true;
                icon[i].name.Tag = true;
                icon[i].name.Visible = true;
                icon[i].icoNameState = 1;
                //RemoveMouseEvents(pic);
                PointDevicesOnClickingIcon(i);
            }
            else
            {
                pic.Tag = false;
                icon[i].name.Tag = false;
                icon[i].name.Visible = false;
                icon[i].icoNameState = 0;
                //AddMouseEvents(pic);
                PointDevicesOnClickingIcon(i);
            }
        }

        private void PointDevicesOnClickingIcon(int i)
        {
            ChangeBackOnClickingIcon();
            //---pointing treenodes--------------------
            foreach (TreeNode node in treeView1.Nodes)
            {
                TreeNode analizNode = node.Nodes[0];
                TreeNode izmerNode = node.Nodes[1];
                if (analizNode.Nodes.Count != 0)
                    foreach (TreeNode rtpsNode in analizNode.Nodes)
                        if (icon[i].name.Text == rtpsNode.Text)
                        {
                            rtpsNode.Parent.Parent.ExpandAll();
                            rtpsNode.BackColor = Color.Aqua;
                        }
                if (izmerNode.Nodes.Count != 0)
                {
                    TreeNodeCollection blrNodes = izmerNode.Nodes;
                    foreach (TreeNode blrNode in blrNodes)
                        foreach (TreeNode rtpsNode in blrNode.Nodes)
                            if (icon[i].name.Text == rtpsNode.Text)
                            {
                                rtpsNode.Parent.Parent.Parent.ExpandAll();
                                rtpsNode.BackColor = Color.Aqua;
                            }
                }
            }
            //---pointing lvitems----------------------
            foreach (ListViewItem lvitem in listView1.Items)
                foreach (ListViewItem.ListViewSubItem lvisub in lvitem.SubItems)
                    if (lvisub.Text == icon[i].name.Text)
                        lvitem.BackColor = Color.Aqua;
            return;
        }

        private void ChangeBackOnClickingIcon()
        {
            foreach (TreeNode node in treeView1.Nodes)
            {
                TreeNode analizNode = node.Nodes[0];
                TreeNode izmerNode = node.Nodes[1];
                if (analizNode.Nodes.Count != 0)
                    foreach (TreeNode rtpsNode in analizNode.Nodes)
                        if (rtpsNode.BackColor != treeView1.BackColor)
                        {
                            rtpsNode.BackColor = treeView1.BackColor;
                        }
                if (izmerNode.Nodes.Count != 0)
                {
                    TreeNodeCollection blrNodes = izmerNode.Nodes;
                    foreach (TreeNode blrNode in blrNodes)
                        foreach (TreeNode rtpsNode in blrNode.Nodes)
                            if (rtpsNode.BackColor != treeView1.BackColor)
                            {
                                rtpsNode.BackColor = treeView1.BackColor;
                            }
                }
            }
            foreach (ListViewItem lvitem in listView1.Items)
                if (lvitem.BackColor != listView1.BackColor)
                    lvitem.BackColor = listView1.BackColor;
            return;
        }
        /*private void ChangeBackOnClickingIcon(int i)
        {
            foreach (TreeNode node in treeView1.Nodes)
            {
                TreeNode analizNode = node.Nodes[0];
                TreeNode izmerNode = node.Nodes[1];
                if (analizNode.Nodes.Count != 0)
                    foreach (TreeNode rtpsNode in analizNode.Nodes)
                        if (icon[i].name.Text == rtpsNode.Text)
                        {
                            rtpsNode.BackColor = treeView1.BackColor;
                        }
                if (izmerNode.Nodes.Count != 0)
                {
                    TreeNodeCollection blrNodes = izmerNode.Nodes;
                    foreach (TreeNode blrNode in blrNodes)
                        foreach (TreeNode rtpsNode in blrNode.Nodes)
                            if (icon[i].name.Text == rtpsNode.Text)
                            {
                                rtpsNode.BackColor = treeView1.BackColor;
                            }
                }
            }
            foreach (ListViewItem lvitem in listView1.Items)
                foreach (ListViewItem.ListViewSubItem lvisub in lvitem.SubItems)
                    if (lvisub.Text == icon[i].name.Text)
                        lvitem.BackColor = listView1.BackColor;
            return;
        }*/

        private void PointDevicesOnEnteringIcon(int i, out int colorState)
        {
            colorState = 0;
            //---pointing treenodes--------------------
            foreach (TreeNode node in treeView1.Nodes)
            {
                TreeNode analizNode = node.Nodes[0];
                TreeNode izmerNode = node.Nodes[1];
                if (analizNode.Nodes.Count != 0)
                    foreach (TreeNode rtpsNode in analizNode.Nodes)
                        if (icon[i].name.Text == rtpsNode.Text)
                        {
                            if (rtpsNode.BackColor == Color.Aqua)
                                colorState = 1;
                            rtpsNode.Parent.Parent.ExpandAll();
                            rtpsNode.BackColor = Color.Orange;
                        }
                if (izmerNode.Nodes.Count != 0)
                {
                    TreeNodeCollection blrNodes = izmerNode.Nodes;
                    foreach (TreeNode blrNode in blrNodes)
                        foreach (TreeNode rtpsNode in blrNode.Nodes)
                            if (icon[i].name.Text == rtpsNode.Text)
                            {
                                if (rtpsNode.BackColor == Color.Aqua)
                                    colorState = 1;
                                rtpsNode.Parent.Parent.Parent.ExpandAll();
                                rtpsNode.BackColor = Color.Orange;
                            }
                }
            }
            //---pointing lvitems----------------------
            foreach (ListViewItem lvitem in listView1.Items)
                foreach (ListViewItem.ListViewSubItem lvisub in lvitem.SubItems)
                    if (lvisub.Text == icon[i].name.Text)
                        lvitem.BackColor = Color.Orange;
        }

        private void ChangeBackOnLeavingIcon(int colorState)
        {
            foreach (TreeNode node in treeView1.Nodes)
            {
                TreeNode analizNode = node.Nodes[0];
                TreeNode izmerNode = node.Nodes[1];
                if (analizNode.Nodes.Count != 0)
                    foreach (TreeNode rtpsNode in analizNode.Nodes)
                        if (rtpsNode.BackColor == Color.Orange)
                        {
                            if (colorState == 0)
                                rtpsNode.BackColor = treeView1.BackColor;
                            else
                                rtpsNode.BackColor = Color.Aqua;
                        }
                if (izmerNode.Nodes.Count != 0)
                {
                    TreeNodeCollection blrNodes = izmerNode.Nodes;
                    foreach (TreeNode blrNode in blrNodes)
                        foreach (TreeNode rtpsNode in blrNode.Nodes)
                            if (rtpsNode.BackColor == Color.Orange)
                            {
                                if (colorState == 0)
                                    rtpsNode.BackColor = treeView1.BackColor;
                                else
                                    rtpsNode.BackColor = Color.Aqua;
                            }
                }
            }
            foreach (ListViewItem lvitem in listView1.Items)
                if (lvitem.BackColor == Color.Orange)
                {
                    if (colorState == 0)
                        lvitem.BackColor = listView1.BackColor;
                    else
                        lvitem.BackColor = Color.Aqua;
                }
        }

        void icon_MouseEnter(object sender, EventArgs e)
        {
            int i = Int32.Parse(((PictureBox)sender).Name);
            PointDevicesOnEnteringIcon(i, out icon[i].colorState);
            if (icon[i].name.Visible)
                return;
            icon[i].name.Visible = true;
            icon[i].name.BringToFront();            
        }

        void icon_MouseLeave(object sender, EventArgs e)
        {
            int i = Int32.Parse(((PictureBox)sender).Name);
            if (!icon[i].name.Visible)
                return;
            if (icon[i].icoNameState == 0)
                icon[i].name.Visible = false;
            ChangeBackOnLeavingIcon(icon[i].colorState);
        }

        private void tim_A_tick(Object myObject, EventArgs myEventArgs)                             //Событие таймера измерителей
        {
            analiz_req.Stop();
            if (Timer_A != null)
                if (Timer_A.ThreadState != ThreadState.Aborted && Timer_A.ThreadState != ThreadState.Stopped && Timer_A.ThreadState != ThreadState.Unstarted)
                {
                    analiz_req.Start();
                }
                else
                {
                    analiz_req.Start();
                    if (!wait_a_trig)
                    {
                        wait_a_trig = true;
                        Timer_A = new Thread(new ThreadStart(req_a_error));
                        Timer_A.Start();

                    }
                    else
                        wait_a_trig = false;
                }
            else
            {
                wait_a_trig = true;
                analiz_req.Start();
                analiz_req.Interval = 5000;
                Timer_A = new Thread(new ThreadStart(req_a_error));
                Timer_A.Start();
            }
            //-----------------------Анализаторы------------------            
        }

        private void req_a_error()                                          //обработка сообщения с анализатора
        {
            Icon_invoke Iinv = icon_set;
            ListViewItem item;
            byte[] cur_st = new byte[2];
            for (int i = 0; i < analiz_count; i++)
            {
                analiz[i].curstate = analiz[i].get_state(analiz[i].ipe);                
                cur_st[0] = analiz[i].curstate[1];
                cur_st[1] = analiz[i].curstate[3];
                if(analiz[i].curstate[0] == 1)
                    cur_st[0] = analiz[i].lstate[0];
                if (analiz[i].curstate[2] == 1)
                    cur_st[1] = analiz[i].lstate[1];                
                if(!check_state(analiz[i].lstate, cur_st))
                {
                    switch (analiz[i].action(analiz[i]))
                    {
                        case 1:                                         //Изменяем на OK
                            list_c--;
                            item = analiz[i].remove(analiz[i]);
                            /*icon[analiz[i].ico].setAnaliz(analiz[i].type);
                            icon[analiz[i].ico].comp();
                            icon[analiz[i].ico].icon.Invoke(Iinv, icon[analiz[i].ico].icon, icon[analiz[i].ico].type);*/  //Состояние!!
                            icon[analiz[i].ico].setAnalizIcon(analiz[i].type, Iinv); 
                            if (item != null)
                            {
                                izm_lrem drem = l_rem;
                                listView1.Invoke(drem, item);
                            }
                            else
                                list_c++;
                            break;
                        case 2:                                         //Было - OK, стало - не OK
                            list_c++;
                            item = analiz[i].add(analiz[i], list_c - 1);
                            /*icon[analiz[i].ico].setAnaliz(analiz[i].type);
                            icon[analiz[i].ico].comp();
                            icon[analiz[i].ico].icon.Invoke(Iinv, icon[analiz[i].ico].icon, icon[analiz[i].ico].type);//Состояние!!*/
                            icon[analiz[i].ico].setAnalizIcon(analiz[i].type, Iinv);
                            if (item != null)
                            {
                                izm_ldel dadd = l_add;
                                try
                                {
                                    listView1.Invoke(dadd, item); //---------------------------------------- исключение с инвоком (InvalidOperationException)
                                }
                                catch (InvalidOperationException)
                                { }
                            }
                            else
                                list_c--;
                            break;
                        case 3:                                         //непонятки
                            if (analiz[i].curstate[4] == 1)
                            {
                                list_c--;
                                item = analiz[i].remove(analiz[i]);
                                if (item != null)
                                {
                                    /*icon[analiz[i].ico].setAnaliz(analiz[i].type);
                                    icon[analiz[i].ico].comp();
                                    icon[analiz[i].ico].icon.Invoke(Iinv, icon[analiz[i].ico].icon, icon[analiz[i].ico].type);*/
                                    icon[analiz[i].ico].setAnalizIcon(analiz[i].type, Iinv);
                                    izm_lrem drem = l_rem;
                                    listView1.Invoke(drem, item);
                                }
                                else
                                    list_c++;
                            }
                            else
                            {
                                err_ret modify = new err_ret();
                                modify = analiz[i].err(analiz[i]);
                                /*icon[analiz[i].ico].setAnaliz(analiz[i].type);
                                icon[analiz[i].ico].comp();
                                icon[analiz[i].ico].icon.Invoke(Iinv, icon[analiz[i].ico].icon, icon[analiz[i].ico].type);*/
                                icon[analiz[i].ico].setAnalizIcon(analiz[i].type, Iinv);
                                izm_cerr derr = l_err;
                                try
                                {
                                    listView1.Invoke(derr, modify.item, modify.err, modify.t_err);
                                }
                                catch (InvalidOperationException)
                                { }
                            }
                            break;
                    }                    
                }                
            }            
        }

        private void tim_I_tick(Object myObject, EventArgs myEventArgs)                             //Событие таймера измерителей
        {
            izmers_req.Stop();
            if (Timer_I != null)
                if (Timer_I.ThreadState != ThreadState.Aborted && Timer_I.ThreadState != ThreadState.Stopped && Timer_I.ThreadState != ThreadState.Unstarted)
                {                    
                    izmers_req.Start();
                }
                else
                {                    
                    izmers_req.Start();
                    if (!wait_i_trig)
                    {
                        wait_i_trig = true;
                        Timer_I = new Thread(new ThreadStart(req_i_error));
                        Timer_I.Start();

                    }
                    else
                        wait_i_trig = false;
                }
            else
            {
                wait_i_trig = true;
                izmers_req.Start();
                izmers_req.Interval = 5000;
                Timer_I = new Thread(new ThreadStart(req_i_error));
                Timer_I.Start();
            }                      
        }

        private void req_i_error()                                  //обработка сообщения с измерителя
        {
            Icon_invoke Iinv = icon_set;
            int con_c = 0;
            for (int i = 0; i < izmers_count; i++)
            {
                con_c = 0;
                int av = izm_soc.Available;
                if (av > 0)
                {
                    byte[] del_buf = new byte[3];
                    while (av-- > 0)
                    {
                        try
                        {
                            izm_soc.Receive(del_buf);
                        }
                        catch (SocketException)
                        {
                        }
                    }
                }
                while (true)
                {
                    try
                    {
                        izm_soc.SendTo(izmers[0].strta, izmers[i].ipe);
                        izm_soc.Receive(izmers[i].errors);
                        break;
                    }
                    catch (SocketException)
                    {
                        if (con_c < count_con)
                            con_c++;
                        else
                            break;
                    }
                }                   
                if (con_c < count_con)
                {
                    izmers[i].errors[3] = 0;
                    if (izmers[i].errors[0] == b0 && izmers[i].errors[1] == b0 && izmers[i].errors[2] == b0 && izmers[i].errors[3] == b0)
                    {
                        if (izmers[i].show == true)
                        {
                            izmers[i].show = false;
                            for (int j = 0; j < izmers[i].lstate.Length; j++)       //Ошибка
                            {
                                izmers[i].lstate[j] = izmers[i].errors[j];
                            }
                            izm_rem(i);
                            icon[izmers[i].ico].setIzmerIcon(1, Iinv);
                            /*icon[izmers[i].ico].setIzmer(1);
                            icon[izmers[i].ico].comp();
                            icon[izmers[i].ico].icon.Invoke(Iinv, icon[izmers[i].ico].icon, icon[izmers[i].ico].type);*/
                        }
                        else
                            icon[izmers[i].ico].setIzmerIcon(1, Iinv);
                        
                    }
                    else if (izmers[i].show == false)
                    {
                        list_c++;
                        izm_add(list_c - 1, i, false);
                        icon[izmers[i].ico].setIzmerIcon(3, Iinv);
                        /*icon[izmers[i].ico].setIzmer(3);
                        icon[izmers[i].ico].comp();
                        icon[izmers[i].ico].icon.Invoke(Iinv, icon[izmers[i].ico].icon, icon[izmers[i].ico].type);*/
                    }
                    else
                    {
                        izm_err(i);
                        icon[izmers[i].ico].setIzmerIcon(3, Iinv);
                        /*icon[izmers[i].ico].setIzmer(3);
                        icon[izmers[i].ico].comp();
                        icon[izmers[i].ico].icon.Invoke(Iinv, icon[izmers[i].ico].icon, icon[izmers[i].ico].type);*/
                    }
                }
                else
                {                                                                       //нет связи
                    icon[izmers[i].ico].setIzmerIcon(5, Iinv);
                    /*icon[izmers[i].ico].setIzmer(5);
                    icon[izmers[i].ico].comp();
                    icon[izmers[i].ico].icon.Invoke(Iinv, icon[izmers[i].ico].icon, icon[izmers[i].ico].type);*/
                    izmers[i].errors[3] = 1;
                    if (izmers[i].show == true)
                        izm_err(i);
                    else
                    {
                        list_c++;
                        izm_add(list_c - 1, i, true);                                                
                    }                                                                        
                }

            }
        }

        private void l_rem(ListViewItem p)
        {
            list_c--;
            p.Remove();            
            listView1.ListViewItemSorter = new ListViewItemComparer(1);
        }

        private void izm_rem(int p)                                                         //Удалить запись
        {            
            izm_lrem d = l_rem;
            listView1.Invoke(d, izmers[p].item);            
        }

        private void l_err(ListViewItem p, string err, string terr)
        {
            string dt = DateTime.Now.ToString();
            if (DateTime.Now.Hour / 10 < 1)
                p.SubItems[1].Text = dt.Substring(0, 5) + '/' + dt.Substring(11, 4);
            else
                p.SubItems[1].Text = dt.Substring(0, 5) + '/' + dt.Substring(11, 5);
            p.SubItems[6].Text = err;
            p.ToolTipText = terr;
            listView1.ListViewItemSorter = new ListViewItemComparer(1);
            for (int i = 0; i < list_c; i++)
                listView1.Items[i].Text = string.Concat(listView1.Items[i].Index);
        }

        private void izm_err(int p)                                                   //Изменились аварии
        {
            string err = "";
            string t_err = "";
            if (check_state(izmers[p].lstate, izmers[p].errors))
                return;
            if (izmers[p].errors[3] == 0)
            {                
                int s = (int)izmers[p].errors[0] + (int)izmers[p].errors[1] + (int)izmers[p].errors[2];
                
                if (s > 1)
                {
                    err = "Аварии";
                }
                else
                    err = "Авария";
                if (izmers[p].errors[0] == b1)
                {
                    err += " A1";
                    t_err += "Отсутствие сигнала GPS";
                }
                if (izmers[p].errors[1] == b1)
                {
                    err += " A2";
                    t_err += "Отсутствие сигнала 10 МГц или 1 PPS от Nimbra 360";
                }
                if (izmers[p].errors[2] == b1)
                {
                    err += " A3";
                    t_err += "Разница превышает значение нормы";
                }
            }
            else
            {
                err = "Нет связи с уcтройством";
                t_err = "Нет связи с уcтройством";
            }
            for (int i = 0; i < izmers[p].lstate.Length; i++)
            {
                izmers[p].lstate[i] = izmers[p].errors[i];
            }
            izm_cerr d = l_err;
            try
            {
                listView1.Invoke(d, izmers[p].item, err, t_err);
            }
            catch (InvalidOperationException)
            { }
            
        }

        private void l_add(ListViewItem p)
        {
            listView1.Items.Add(p);
            listView1.ListViewItemSorter = new ListViewItemComparer(1);
            //for (int i = 0; i < list_c; i++)
            for (int i = 0; i < listView1.Items.Count; i++)
                listView1.Items[i].Text = string.Concat(listView1.Items[i].Index);
        }

        private void izm_add(int c, int p, bool a4)                                                  //Добавить запись
        {
            izmers[p].show = true;
            izmers[p].item = new ListViewItem(c.ToString());
            izmers[p].num = c;
            string dt = DateTime.Now.ToString();
            if (DateTime.Now.Hour/10 < 1)
                izmers[p].item.SubItems.Add(dt.Substring(0, 5) + '/' + dt.Substring(11, 4));
            else
                izmers[p].item.SubItems.Add(dt.Substring(0, 5) + '/' + dt.Substring(11, 5));
            izmers[p].item.SubItems.Add(izmers[p].obl);
            izmers[p].item.SubItems.Add(izmers[p].blr);
            izmers[p].item.SubItems.Add(izmers[p].name);
            izmers[p].item.SubItems.Add("Измерители");  
            izmers[p].item.ToolTipText = "";
            string err = "";
            if (!a4)
            {
                izmers[p].a4 = false;
                int s = 0;
                s += (int)izmers[p].errors[0];
                s += (int)izmers[p].errors[1];
                s += (int)izmers[p].errors[2];
                if (s > 1)
                {
                    err = "Аварии";
                }
                else                    
                    err = "Авария";
                if (izmers[p].errors[0] == b1)
                {
                    err += " A1";
                    izmers[p].item.ToolTipText += "Отсутствие сигнала GPS ";
                }
                if (izmers[p].errors[1] == b1)
                {
                    err += " A2";
                    izmers[p].item.ToolTipText += "Отсутствие сигнала 10 МГц или 1 PPS от Nimbra 360 ";
                }
                if (izmers[p].errors[2] == b1)
                {
                    err += " A3";
                    izmers[p].item.ToolTipText += "Разница превышает значение нормы";
                }                    
            }
            else
            {
                err = "Нет связи с уcтройством";
                izmers[p].a4 = true;
                izmers[p].item.ToolTipText = "Нет связи с уcтройством";
            }
            for (int i = 0; i < izmers[p].lstate.Length; i++)
            {
                izmers[p].lstate[i] = izmers[p].errors[i];
            }
            izmers[p].item.SubItems.Add(err);
            izm_ldel d = l_add;
            try
            {
                listView1.Invoke(d, izmers[p].item); //---------------------------------------- исключение с инвоком (InvalidOperationException)
            }
            catch (InvalidOperationException) 
            { }
        }

        private void izmers_create(string m_obl)
        {
            string oblast = "";
            string[] obl;
            int i = 0;
            int u = 0, u1;
            string dev = "";
            string name = "";
            string ipstr = "";
            string blr = "";
            StreamWriter ws = new StreamWriter(@"resources\izmers.csv", false, Encoding.GetEncoding("Windows-1251"));
            ws.WriteLine("");
            obl = File.ReadAllLines(@"resources\maps\Brest.ini", Encoding.GetEncoding("Windows-1251"));
            switch (m_obl)
            {                
                    case "brest":
                        obl = File.ReadAllLines(@"resources\maps\Brest.ini", Encoding.GetEncoding("Windows-1251"));
                        break;
                    case "viteb":
                        obl = File.ReadAllLines(@"resources\maps\Vitebsk.ini", Encoding.GetEncoding("Windows-1251"));
                        break;
                    case "gomel":
                        obl = File.ReadAllLines(@"resources\maps\Gomel.ini", Encoding.GetEncoding("Windows-1251"));
                        break;
                    case "grodn":
                        obl = File.ReadAllLines(@"resources\maps\Grodno.ini", Encoding.GetEncoding("Windows-1251"));
                        break;
                    case "minsk":
                        obl = File.ReadAllLines(@"resources\maps\Minsk.ini", Encoding.GetEncoding("Windows-1251"));
                        break;
                    case "mogil":
                        obl = File.ReadAllLines(@"resources\maps\Mogilev.ini", Encoding.GetEncoding("Windows-1251"));
                        break;                                
            }
            i = 0;
            while (i < obl.Length)
            {
                switch (obl[i])
                {
                    case "[Измерители]":
                        dev = "izm";
                        i++;
                        break;
                    case "[Анализаторы]":
                        dev = "anal";
                        i++;
                        break;
                    case "":
                        i++;
                        break;
                    default:
                        if (dev != "izm")
                        {
                            i++;
                            break;
                        }
                        u = 0; u1 = 0;
                        while (obl[i][u] != '=')
                            u++;
                        name = obl[i].Substring(0, u);
                        u++;
                        u1 = u;

                        while (obl[i][u1] != ',')
                            u1++;
                        ipstr = obl[i].Substring(u, u1 - u);

                        u1++;
                        while (obl[i].Substring(u, 3) != "BLR")
                            u++;
                        try
                        {
                            blr = obl[i].Substring(u, 5);
                        }
                        catch (ArgumentOutOfRangeException)
                        {
                            blr = obl[i].Substring(u, 4);
                        }
                        ws.WriteLine(ipstr + ";" + name + ";" + blr + ";" + oblast);                              //Запись строки
                        u = 1;
                        i++;
                        break;
                }
            }            
            ws.Close();
        }

        private void treeView1_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)                   //Двойной щелчок по узлу дерева
        {
            try
            {
                if (e.Node.Parent.Text.Substring(0, 3) == "BLR")
                {
                    IPAddress ip;
                    ipstr = e.Node.Tag.ToString();
                    ip = IPAddress.Parse(ipstr);
                    if (!f4)
                    {
                        f4 = true;
                        form4 = new IzmersMonitoringForm(new f4ChangeEventDelegate(f4ChangeEvent), new fclose(f4close));
                        form4.Owner = this;
                        form4.Enabled = true;                        
                        form4.Show();
                        if (AddIzmer != null)
                            AddIzmer(ip);
                    }
                    else
                    {
                        if (AddIzmer != null)
                            AddIzmer(ip);
                    }
                }

                else try
                    {
                        if (e.Node.Parent.Text.Substring(0, 10) == "Анализатор")
                        {
                            System.Diagnostics.Process.Start("iexplore.exe", "http://" + e.Node.Tag.ToString() + "/dvms/dvms.jnlp");
                        }
                    }
                    catch (ArgumentOutOfRangeException)
                    { }
            }
            catch (NullReferenceException)
            { }
        }

        private void Form2_FormClosing(object sender, FormClosingEventArgs e)
        {
            {
                int i;
                if (Directory.Exists(@"resources\temp_logs"))
                {
                    string[] gf = Directory.GetFiles(@"resources\temp_logs");
                    if(gf.Length != 0)
                        for (i = 0; i < gf.Length; i++)
                        {
                            File.Delete(gf[i]);
                        }
                }
            }
            try
            {
                analiz_req.Stop();
                Timer_A.Abort();
                Timer_A.Join();
                izmers_req.Stop();
                Timer_I.Abort();
                Timer_I.Join();
            }
            catch (NullReferenceException)
            { }
            if (f6)
                form6.Close();
            //Initiate_CLOSING();
            //Application.Exit();
            var newAuth = new AuthentificationForm();
            newAuth.Show();
        }

        private void журналToolStripMenuItem_Click(object sender, EventArgs e)
        {
            /*Form5 form5;
            if (!f5)
            {
                f5 = true;
                form5 = new Form5(new fclose(f5close), new form_delegate(form_send));
                form5.Owner = this;
                form5.Enabled = true;
                form5.Show();
            }*/            
            if (!f6)
            {
                f6 = true;
                //form6 = new Form6(new fclose(f6close), options.oblast);
                form6 = new JournalForm(new fclose(f6close), options);
                form6.Owner = this;
                form6.Icon = this.Icon;
                form6.Enabled = true;
                form6.Show();
            }
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            TreeView tn = (TreeView)sender;
            if (tn.SelectedNode.Text.Substring(0, 5) != "РТПС ")
            {
                foreach (Icons ic in icon)
                    if (!(bool)ic.name.Tag)
                    {
                        ic.name.Visible = false;
                    }
                return;
            }
            foreach (Icons ic in icon)
                if (!(bool)ic.name.Tag)
                {
                    if (ic.name.Text == tn.SelectedNode.Text)
                    {
                        if (!ic.name.Visible)
                            ic.name.Visible = true;
                        ic.name.BringToFront();
                    }
                    else
                        ic.name.Visible = false;
                }
                else
                    if (ic.name.Text == tn.SelectedNode.Text)                    
                        ic.name.BringToFront();
        }

        private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Button != MouseButtons.Right)
                return;
            treeView1.SelectedNode = e.Node;
            if (options.access != 1)
                return;            
            try
            {
                if (((TreeView)sender).SelectedNode.Parent.Text.Contains("BLR"))
                {
                    curListViewItemIP = (string)((TreeView)sender).SelectedNode.Tag;
                    curListViewItemName = ((TreeView)sender).SelectedNode.Text;
                    //contextMenuStrip1.Show(MousePosition, ToolStripDropDownDirection.Right);
                }
            }
            catch (NullReferenceException)
            { }
        }

        //private void изменитьПараметрыToolStripMenuItem_Click(object sender, EventArgs e)
        //{
        //    IPAddress ip;
        //    ip = IPAddress.Parse(curListViewItemIP);
        //    string name = curListViewItemName;
        //    /*if (!IPAddress.TryParse(textBox2.Text, out ip))
        //    {
        //        MessageBox.Show("Введен некорректный IP-адрес");
        //        return;
        //    }*/
        //    /*if (!f7)
        //    {
        //        f7 = true;
        //        Form7 form7 = new Form7(ip, name);
        //        form9.Owner = this;
        //        this.Enabled = false;
        //        form9.Show();
        //    }*/
        //    IzmersParamsChangeForm form7 = new IzmersParamsChangeForm(ip, name);
        //    form7.Owner = this;
        //    form7.ShowDialog();
        //}

        private void оПрограммеToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form about;
            about = new AboutForm();
            about.Icon = this.Icon;
            try
            {
                about.ShowDialog();
            }
            catch (InvalidOperationException)
            { }
        }
        
    }

    
}
